package com.yq.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @ClassName ScatteringAndGatheringTest
 * @Description Buffer的分散和聚集， 操作更快捷
 * @Author yaoqiang
 * @Date 2021/3/24 14:34
 * @Version 1.0
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //使用serverSocketChannel和socketChannel
        ServerSocketChannel open = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到socket
        open.socket().bind(inetSocketAddress);
        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        SocketChannel socketChannel = open.accept();
int messageLength=8;
        while (true) {
            int byteRead=0;
            while (byteRead<messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead+=read;
                System.out.println(read);
                //使用流打印，看看当前这个buffer的position和limit
                Arrays.asList(byteBuffers).stream().map(buffer->"position="+buffer.position()+",limit="+buffer.limit()).forEach(System.out::println);
            }
            Arrays.asList(byteBuffers).forEach(buffer->buffer.flip());
            //将数据读出显示到客户端
            long byteWrite=0;
            while (byteWrite<messageLength){
                long l=socketChannel.write(byteBuffers);
                byteWrite+=l;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(buffer->{buffer.clear();});
            System.out.println("byteRead="+byteRead+",byteWrite="+byteWrite+",messageLength"+messageLength);
        }
    }
}
